<template>
    <div class="device-statistic-demo">
        <!-- 查询表单 -->
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="75px">
            <el-form-item class="search-card">
                <el-date-picker v-model="daterangeTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    @click="
                        deviceListHistory();
                        handleSearch();
                    "
                >
                    查询
                </el-button>
            </el-form-item>
        </el-form>

        <!-- 统计图表展示 -->
        <div v-for="(item, index) in staticList" :key="index" style="margin-bottom: 30px">
            <el-card shadow="hover" :body-style="{ padding: '10px 0px', overflow: 'auto' }" v-loading="loading">
                <div :ref="'statisticMap' + index" style="height: 300px; width: 100%"></div>
            </el-card>
        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts';
import { listHistory } from '@/api/iot/device';
export default {
    name: 'DeviceStatistic',
    props: {
        // 可以接收设备ID等参数，用于后续扩展
        productId: {},
        serialNumber: {},
        deviceList: [],
    },
    data() {
        return {
            loading: false,
            // 模拟的静态数据
            staticList: [
                {
                    id: 'temperature',
                    name: 'TVOC统计',
                    datatype: { unit: 'mg/m3' },
                },
                {
                    id: 'pressure',
                    name: '甲醛统计',
                    datatype: { unit: 'mg/m3' },
                },
                {
                    id: 'humidity',
                    name: 'PM10统计',
                    datatype: { unit: 'ug/m3' },
                },
                {
                    id: 'humidity1',
                    name: 'PM2.2统计',
                    datatype: { unit: 'ug/m3' },
                },
                {
                    id: 'humidity2',
                    name: '二氧化碳统计',
                    datatype: { unit: 'ppm' },
                },
                {
                    id: 'humidity3',
                    name: '空气湿度统计',
                    datatype: { unit: '%' },
                },
                {
                    id: 'humidity4',
                    name: '空气温度统计',
                    datatype: { unit: '℃' },
                },
            ],
            // 图表实例集合
            chartInstances: [],
            // 时间范围
            daterangeTime: [this.getTime(), this.getTime()],
            // 查询参数
            queryParams: {
                // 可以添加其他查询参数
            },
        };
    },
    mounted() {
        this.initCharts();
        this.loadMockData();
    },
    methods: {
        deviceListHistory() {
            // 格式化日期时间，将日期转换为完整的时间格式
            const beginTime = this.daterangeTime[0] ? this.daterangeTime[0] + ' 00:00:00' : '';
            const endTime = this.daterangeTime[1] ? this.daterangeTime[1] + ' 23:59:59' : '';
            listHistory({
                serialNumber: this.serialNumber,
                beginTime: beginTime,
                endTime: endTime,
                productId: this.productId,
            }).then((response) => {
                if (response.code === 200) {
                    // console.log(response.data);
                }
            });
        },
        /** 获取当前日期 */
        getTime() {
            let date = new Date();
            let y = date.getFullYear();
            let m = date.getMonth() + 1;
            let d = date.getDate();
            m = m < 10 ? '0' + m : m;
            d = d < 10 ? '0' + d : d;
            return y + '-' + m + '-' + d;
        },

        /** 初始化图表 */
        initCharts() {
            this.chartInstances = [];

            this.$nextTick(() => {
                this.staticList.forEach((item, index) => {
                    const chartDom = this.$refs['statisticMap' + index];
                    if (chartDom && chartDom[0]) {
                        const chart = echarts.init(chartDom[0]);
                        this.chartInstances[index] = chart;

                        // 设置基础图表配置
                        const option = this.getChartOption(item, index);
                        chart.setOption(option);
                    }
                });
            });
        },

        /** 获取图表配置 */
        getChartOption(item, index) {
            const colors = ['#1890FF', '#91CB74', '#FAC858', '#EE6666', '#73C0DE', '#3CA272', '#FC8452', '#9A60B4', '#ea7ccc'];

            return {
                animationDurationUpdate: 3000,
                tooltip: {
                    trigger: 'axis',
                    textStyle: {
                        color: '#fff',
                    },
                },
                title: {
                    left: 'center',
                    text: `${item.name}统计 （单位 ${item.datatype?.unit || '无'}）`,
                    textStyle: {
                        color: '#fff',
                    },
                },
                grid: {
                    top: '80px',
                    left: '40px',
                    right: '20px',
                    bottom: '60px',
                    containLabel: true,
                },
                toolbox: {
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none',
                        },
                        restore: {},
                        saveAsImage: {},
                    },
                },
                xAxis: {
                    type: 'time',
                    axisLabel: {
                        color: '#fff',
                    },
                },
                yAxis: {
                    type: 'value',
                    scale: true,
                    axisLabel: {
                        formatter: function (value) {
                            return value.toFixed(2);
                        },
                        color: '#fff',
                    },
                },
                dataZoom: [
                    {
                        type: 'inside',
                        start: 0,
                        end: 100,
                    },
                    {
                        start: 0,
                        end: 100,
                    },
                ],
                series: [
                    {
                        name: item.name,
                        type: 'line',
                        symbol: 'none',
                        sampling: 'lttb',
                        itemStyle: {
                            color: index > 9 ? colors[0] : colors[index],
                        },
                        areaStyle: {},
                        data: [], // 初始为空，后续加载模拟数据
                    },
                ],
            };
        },

        /** 加载模拟数据 */
        loadMockData() {
            this.loading = true;

            // 模拟异步数据加载
            setTimeout(() => {
                this.staticList.forEach((item, index) => {
                    const chart = this.chartInstances[index];
                    if (chart) {
                        // 生成模拟的时间序列数据
                        const mockData = this.generateMockData(item);

                        chart.setOption({
                            series: [
                                {
                                    data: mockData,
                                },
                            ],
                        });

                        // 确保图表重绘
                        chart.resize();
                    }
                });

                this.loading = false;
            }, 1000);
        },

        /** 生成模拟数据 */
        generateMockData(item) {
            const data = [];
            const baseValue = this.getBaseValue(item.id);
            const now = new Date();

            // 生成过去24小时的数据
            for (let i = 24; i >= 0; i--) {
                const time = new Date(now.getTime() - i * 60 * 60 * 1000);
                // 添加一些随机波动
                const value = baseValue + (Math.random() - 0.5) * 10;

                data.push([time.getTime(), value]);
            }

            return data;
        },

        /** 根据数据类型获取基础值 */
        getBaseValue(type) {
            const baseValues = {
                temperature: 25, // 温度基础值25°C
                pressure: 100, // 压力基础值100kPa
                humidity: 60, // 湿度基础值60%
            };

            return baseValues[type] || 50;
        },

        /** 查询按钮点击事件 */
        handleSearch() {
            this.loadMockData();
        },

        /** 窗口大小变化时重绘图表 */
        handleResize() {
            this.chartInstances.forEach((chart) => {
                if (chart) {
                    chart.resize();
                }
            });
        },
    },

    beforeDestroy() {
        // 清理图表实例
        this.chartInstances.forEach((chart) => {
            if (chart) {
                chart.dispose();
            }
        });

        // 移除事件监听
        window.removeEventListener('resize', this.handleResize);
    },

    created() {
        // 添加窗口大小变化监听
        window.addEventListener('resize', this.handleResize);
    },
};
</script>

<style lang="scss" scoped>
.device-statistic-demo {
    width: 100%;
    padding: 20px;
    background-color: rgba(0, 11, 61, 0.79);
}
.el-card {
    margin-bottom: 20px;
}

.el-form {
    margin-bottom: 20px;
}
::v-deep .el-card__body {
    background-color: rgba(0, 11, 61, 1);
}
::v-deep .el-card {
    border-color: #486ff2;
}
.search-card {
    // background: rgba(0, 11, 61, 0.8);
    // color: #fff;
    // border: none;
    // margin-bottom: 15px;
    // padding: 3px 0;

    ::v-deep .el-input__inner {
        background: rgba(255, 255, 255, 0.1);
        border-color: rgba(22, 93, 255, 0.5);
        color: #fff; /* 文字颜色 */
    }
    ::v-deep .el-range-editor--medium .el-range-input {
        background: none;
        color: #fff; /* 文字颜色 */
    }
}
</style>
